package com.excellent.ImageIdentification;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class OcrClient {
    private static final String OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";

    public static String recognizeText(String imageBase64, String accessToken) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(OCR_URL);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            String jsonInputString = String.format("image=%s&access_token=%s", imageBase64, accessToken);
            StringEntity input = new StringEntity(jsonInputString);
            input.setContentType("application/json");
            httpPost.setEntity(input);

            HttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        }
    }
}